package com.itany.ums;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBUtil {

    String driverClassName = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/ums?useUnicode=true&characterEncoding=utf8";
    String username = "root";
    String password = "root";

    public List<User> selectAll(){
        List<User> list = new ArrayList<>();
        try {
            Class.forName(driverClassName);
            Connection conn = DriverManager.getConnection(url,username,password);
            PreparedStatement ps = conn.prepareStatement("select * from t_user");
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                u.setPwd(rs.getString("pwd"));
                u.setAge(rs.getInt("age"));
                u.setHobby(rs.getString("hobby"));
                u.setInfo(rs.getString("info"));
                u.setSex(rs.getString("sex"));
                list.add(u);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public void insert(User user){
        try {
            Class.forName(driverClassName);
            Connection conn = DriverManager.getConnection(url,username,password);
            PreparedStatement ps = conn.prepareStatement("insert into t_user values (null,?,?,?,?,?,?)");
            ps.setString(1,user.getName());
            ps.setString(2,user.getPwd());
            ps.setInt(3,user.getAge());
            ps.setString(4,user.getHobby());
            ps.setString(5,user.getInfo());
            ps.setString(6,user.getSex());
            ps.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void update(User user){

    }

    public void deleteById(int id){

    }

    public User selectById(int id){

        return null;
    }

    public static void main(String[] args) {
        System.out.println(new DBUtil().selectAll());
    }
}
